<template>
  <div class="monitor-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <h1 class="page-title">系统监控面板</h1>
      </el-col>
    </el-row>

    <!-- 系统健康状态概览 -->
    <el-row :gutter="20" class="dashboard-row">
      <el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="8">
        <el-card
          class="health-card"
          :class="healthReport.status === 'NORMAL' ? 'healthy' : 'unhealthy'"
        >
          <template #header>
            <div class="card-header">
              <span>系统健康状态</span>
              <el-tag
                :type="healthReport.status === 'NORMAL' ? 'success' : 'danger'"
              >
                {{ healthReport.status === "NORMAL" ? "正常" : "异常" }}
              </el-tag>
            </div>
          </template>
          <div class="health-report">
            <div class="report-item">
              <span class="report-label">平均CPU使用率：</span>
              <span class="report-value">
                {{
                  typeof healthReport.avgCpuUsage === "number"
                    ? healthReport.avgCpuUsage.toFixed(2)
                    : "0.00"
                }}%
              </span>
            </div>
            <div class="report-item">
              <span class="report-label">最高CPU使用率：</span>
              <span class="report-value">
                {{
                  typeof healthReport.maxCpuUsage === "number"
                    ? healthReport.maxCpuUsage.toFixed(2)
                    : "0.00"
                }}%
              </span>
            </div>
            <div class="report-item">
              <span class="report-label">平均内存使用率：</span>
              <span class="report-value">
                {{
                  typeof healthReport.avgMemoryUsage === "number"
                    ? healthReport.avgMemoryUsage.toFixed(2)
                    : "0.00"
                }}%
              </span>
            </div>
            <div class="report-item">
              <span class="report-label">最高内存使用率：</span>
              <span class="report-value">
                {{
                  typeof healthReport.maxMemoryUsage === "number"
                    ? healthReport.maxMemoryUsage.toFixed(2)
                    : "0.00"
                }}%
              </span>
            </div>
            <div class="report-item">
              <span class="report-label">平均磁盘使用率：</span>
              <span class="report-value">
                {{
                  typeof healthReport.avgDiskUsage === "number"
                    ? healthReport.avgDiskUsage.toFixed(2)
                    : "0.00"
                }}%
              </span>
            </div>
            <div class="report-item">
              <span class="report-label">告警次数：</span>
              <span class="report-value">{{
                healthReport.alertCount || 0
              }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 当前系统指标 -->
      <el-col :xs="24" :sm="24" :md="24" :lg="16" :xl="16">
        <el-card class="metrics-card">
          <template #header>
            <div class="card-header">
              <span>当前系统指标</span>
  <div>
                <span class="update-time"
                  >更新时间:
                  {{ formatDateTime(currentMetrics.timestamp) }}</span
                >
                <el-button
                  size="small"
                  type="primary"
                  @click="refreshMetrics"
                  :loading="loading.metrics"
                >
                  刷新
                </el-button>
              </div>
            </div>
          </template>
          <div class="metrics-dashboard">
            <div class="metric-gauge">
              <div class="metric-title">CPU使用率</div>
              <el-progress
                type="dashboard"
                :percentage="Math.round(currentMetrics.cpuUsage || 0)"
                :color="getProgressColor(currentMetrics.cpuUsage || 0)"
              />
              <div class="metric-value">
                {{ currentMetrics.cpuUsage?.toFixed(2) }}%
              </div>
            </div>
            <div class="metric-gauge">
              <div class="metric-title">内存使用率</div>
              <el-progress
                type="dashboard"
                :percentage="Math.round(currentMetrics.memoryUsage || 0)"
                :color="getProgressColor(currentMetrics.memoryUsage || 0)"
              />
              <div class="metric-value">
                {{ currentMetrics.memoryUsage?.toFixed(2) }}%
              </div>
            </div>
            <div class="metric-gauge">
              <div class="metric-title">磁盘使用率</div>
              <el-progress
                type="dashboard"
                :percentage="Math.round(currentMetrics.diskUsage || 0)"
                :color="getProgressColor(currentMetrics.diskUsage || 0)"
              />
              <div class="metric-value">
                {{ currentMetrics.diskUsage?.toFixed(2) }}%
              </div>
            </div>
          </div>
          <el-divider>详细指标</el-divider>
          <div class="metrics-detail">
            <div class="metric-detail-item">
              <div class="detail-label">当前活跃线程数：</div>
              <div class="detail-value">
                {{ currentMetrics.threadCount || 0 }}
              </div>
            </div>
            <div class="metric-detail-item">
              <div class="detail-label">堆内存使用率：</div>
              <div class="detail-value">
                <el-progress
                  :percentage="Math.round(currentMetrics.heapUsage || 0)"
                  :color="getProgressColor(currentMetrics.heapUsage || 0)"
                />
                {{ currentMetrics.heapUsage?.toFixed(2) }}%
              </div>
            </div>
            <div class="metric-detail-item">
              <div class="detail-label">非堆内存使用率：</div>
              <div class="detail-value">
                <el-progress
                  :percentage="Math.round(currentMetrics.nonHeapUsage || 0)"
                  :color="getProgressColor(currentMetrics.nonHeapUsage || 0)"
                />
                {{ currentMetrics.nonHeapUsage?.toFixed(2) }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 告警信息表格 -->
    <el-row :gutter="20" class="dashboard-row">
      <el-col :span="24">
        <el-card class="alert-card">
          <template #header>
            <div class="card-header">
              <span>系统告警信息</span>
              <el-button
                size="small"
                type="primary"
                @click="refreshAlerts"
                :loading="loading.alerts"
              >
                刷新
              </el-button>
            </div>
          </template>
          <el-table
            :data="alerts.records || []"
            style="width: 100%"
            v-loading="loading.alerts"
          >
            <el-table-column type="index" label="#" width="60" />
            <el-table-column prop="id" label="告警ID" width="80" />
            <el-table-column prop="type" label="告警类型" width="120">
              <template #default="scope">
                <el-tag size="small">{{ getAlertType(scope.row.type) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="level" label="告警级别" width="100">
              <template #default="scope">
                <el-tag :type="getAlertLevelType(scope.row.level)" size="small">
                  {{ getAlertLevel(scope.row.level) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="message" label="告警信息" min-width="250" />
            <el-table-column prop="createTime" label="告警时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.createTime) }}
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              v-model:currentPage="pagination.pageNum"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="alerts.total || 0"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 历史监控数据 -->
    <el-row :gutter="20" class="dashboard-row">
      <el-col :span="24">
        <el-card class="history-card">
          <template #header>
            <div class="card-header">
              <span>历史监控数据</span>
              <div class="date-range-picker">
                <!-- 修改点1：日期选择器格式调整 -->
    <el-date-picker
      v-model="dateRange"
      type="datetimerange"
      value-format="YYYY-MM-DD HH:mm:ss"
      :default-time="[new Date(2000, 0, 1, 0, 0, 0), new Date(2000, 0, 1, 23, 59, 59)]"
    />
                <el-button
                  type="primary"
                  @click="fetchHistoricalData"
                  :loading="loading.historical"
                >
                  查询
                </el-button>
              </div>
            </div>
          </template>

          <div v-if="historicalData.length === 0" class="empty-data">
            <el-empty description="暂无历史数据" />
          </div>

          <div v-else class="chart-container">
            <!-- 这里可以使用 ECharts 或其他图表库展示历史数据 -->
            <div class="metrics-table">
              <el-table
                :data="historicalData"
                style="width: 100%"
                v-loading="loading.historical"
              >
                <el-table-column type="index" label="#" width="60" />
                <el-table-column prop="timestamp" label="时间" width="180">
                  <template #default="scope">
                    {{ formatDateTime(scope.row.timestamp) }}
                  </template>
                </el-table-column>
                <el-table-column prop="cpuUsage" label="CPU使用率" width="120">
                  <template #default="scope">
                    {{ scope.row.cpuUsage?.toFixed(2) }}%
                  </template>
                </el-table-column>
                <el-table-column
                  prop="memoryUsage"
                  label="内存使用率"
                  width="120"
                >
                  <template #default="scope">
                    {{ scope.row.memoryUsage?.toFixed(2) }}%
                  </template>
                </el-table-column>
                <el-table-column
                  prop="diskUsage"
                  label="磁盘使用率"
                  width="120"
                >
                  <template #default="scope">
                    {{ scope.row.diskUsage?.toFixed(2) }}%
                  </template>
                </el-table-column>
                <el-table-column
                  prop="threadCount"
                  label="线程数"
                  width="100"
                />
                <el-table-column
                  prop="heapUsage"
                  label="堆内存使用率"
                  width="120"
                >
                  <template #default="scope">
                    {{ scope.row.heapUsage?.toFixed(2) }}%
                  </template>
                </el-table-column>
                <el-table-column
                  prop="nonHeapUsage"
                  label="非堆内存使用率"
                  width="120"
                >
                  <template #default="scope">
                    {{ scope.row.nonHeapUsage?.toFixed(2) }}%
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  getSystemMonitor,
  getHistoricalMonitor,
  getHealthMonitor,
  getAlertsMonitor,
} from "@/api/systemMonitor";
import { ref, onMounted, computed, onBeforeUnmount } from "vue";
import { ElMessage } from "element-plus"; // 确保引入ElMessage
export default {
  name: "ServiceMonitor",
  setup() {
    // 数据定义
    const dateRange = ref([]);
    const historicalData = ref([]);
    const currentMetrics = ref({
      id: null,
      cpuUsage: 0,
      memoryUsage: 0,
      diskUsage: 0,
      threadCount: 0,
      heapUsage: 0,
      nonHeapUsage: 0,
      timestamp: null,
    });

    const healthReport = ref({
      reportTime: null,
      avgCpuUsage: 0,
      maxCpuUsage: 0,
      avgMemoryUsage: 0,
      maxMemoryUsage: 0,
      avgDiskUsage: 0,
      alertCount: 0,
      status: "NORMAL",
    });

    const alerts = ref({
      records: [],
      total: 0,
      current: 1,
      size: 10,
    });

    const pagination = ref({
      pageNum: 1,
      pageSize: 10,
    });

    const loading = ref({
      metrics: false,
      health: false,
      alerts: false,
      historical: false,
    });

    let refreshTimer = null;

    // 计算属性和工具函数
    const getProgressColor = (percentage) => {
      if (percentage < 60) return "#67C23A";
      if (percentage < 80) return "#E6A23C";
      return "#F56C6C";
    };

    const getAlertLevelType = (level) => {
      const types = {
        0: "info",
        1: "warning",
        2: "danger",
      };
      return types[level] || "info";
    };

    const getAlertLevel = (level) => {
      const levels = {
        0: "一般",
        1: "警告",
        2: "严重",
      };
      return levels[level] || "未知";
    };

    const getAlertType = (type) => {
      const types = {
        0: "系统",
        1: "CPU",
        2: "内存",
        3: "磁盘",
        4: "网络",
      };
      return types[type] || "其他";
    };

    const formatDateTime = (dateTime) => {
      if (!dateTime) return "未知";
      // 判断是否为字符串，如果是则转换为日期对象
      const date = typeof dateTime === "string" ? new Date(dateTime) : dateTime;
      try {
        return new Intl.DateTimeFormat("zh-CN", {
          year: "numeric",
          month: "2-digit",
          day: "2-digit",
          hour: "2-digit",
          minute: "2-digit",
          second: "2-digit",
          hour12: false,
        }).format(date);
      } catch (e) {
        console.error("日期格式化错误:", e);
        return "格式化错误";
      }
    };

    // 数据获取方法
    const fetchMetrics = async () => {
      loading.value.metrics = true;
      try {
        const { data } = await getSystemMonitor();
        if (data.success && data.data) {
          currentMetrics.value = data.data;
          console.log("获取到的系统指标:", data.data);
        } else {
          console.error("获取系统指标失败:", data.message);
        }
      } catch (error) {
        console.error("获取系统指标请求出错:", error);
      } finally {
        loading.value.metrics = false;
      }
    };

    const fetchHealth = async () => {
      loading.value.health = true;
      try {
        const { data } = await getHealthMonitor();
        if (data?.success && data?.data) {
          // 确保数值类型正确
          healthReport.value = {
            reportTime: data.data.reportTime
              ? new Date(data.data.reportTime)
              : new Date(),
            avgCpuUsage: parseFloat(data.data.avgCpuUsage) || 0,
            maxCpuUsage: parseFloat(data.data.maxCpuUsage) || 0,
            avgMemoryUsage: parseFloat(data.data.avgMemoryUsage) || 0,
            maxMemoryUsage: parseFloat(data.data.maxMemoryUsage) || 0,
            avgDiskUsage: parseFloat(data.data.avgDiskUsage) || 0,
            alertCount: parseInt(data.data.alertCount) || 0,
            status: data.data.status || "NORMAL",
          };
          console.log("获取到的健康报告:", healthReport.value);
        } else {
          console.error("获取健康报告失败:", data?.message);
          // 返回默认值以防错误
          healthReport.value = {
            reportTime: new Date(),
            avgCpuUsage: 0,
            maxCpuUsage: 0,
            avgMemoryUsage: 0,
            maxMemoryUsage: 0,
            avgDiskUsage: 0,
            alertCount: 0,
            status: "NORMAL",
          };
        }
      } catch (error) {
        console.error("获取健康报告请求出错:", error);
        // 返回默认值以防错误
        healthReport.value = {
          reportTime: new Date(),
          avgCpuUsage: 0,
          maxCpuUsage: 0,
          avgMemoryUsage: 0,
          maxMemoryUsage: 0,
          avgDiskUsage: 0,
          alertCount: 0,
          status: "NORMAL",
        };
      } finally {
        loading.value.health = false;
      }
    };

    const fetchAlerts = async () => {
      loading.value.alerts = true;
      try {
        const { data } = await getAlertsMonitor(
          pagination.value.pageNum,
          pagination.value.pageSize
        );
        if (data.success && data.data) {
          alerts.value = data.data;
          console.log("获取到的告警信息:", data.data);
        } else {
          console.error("获取告警信息失败:", data.message);
        }
      } catch (error) {
        console.error("获取告警信息请求出错:", error);
      } finally {
        loading.value.alerts = false;
      }
    };
    const initDefaultDateRange = () => {
      const end = new Date();
      const start = new Date(end.getTime() - 24 * 60 * 60 * 1000);

      // 格式化为 YYYY-MM-DD HH:mm:ss
      const formatDate = (date) => {
        return date.toISOString().replace("T", " ").substring(0, 19);
      };

      dateRange.value = [formatDate(start), formatDate(end)];
    };
    const fetchHistoricalData = async () => {
      if (!dateRange.value || dateRange.value.length !== 2) {
        ElMessage.warning("请选择有效的时间范围");
        return;
      }

      loading.value.historical = true;
      try {
        const [startTime, endTime] = dateRange.value;
        const { data } = await getHistoricalMonitor(startTime, endTime);

        console.log("获取到的历史数据:", data);
        if (data.success && Array.isArray(data.data)) {
          // 处理日期
          historicalData.value = data.data.map((item) => ({
            ...item,
            timestamp: item.timestamp ? new Date(item.timestamp) : null,
            cpuUsage: Number(item.cpuUsage || 0),
            memoryUsage: Number(item.memoryUsage || 0),
            diskUsage: Number(item.diskUsage || 0),
            threadCount: Number(item.threadCount || 0),
            heapUsage: Number(item.heapUsage || 0),
            nonHeapUsage: Number(item.nonHeapUsage || 0),
          }));
          console.log("获取到的历史数据:", historicalData.value);
        } else {
          console.error("获取历史数据失败:", data.message);
          ElMessage.error(`获取历史数据失败: ${data.message || "未知错误"}`);
          historicalData.value = [];
        }
      } catch (error) {
        console.error("获取历史数据请求出错:", error);
        ElMessage.error(`历史数据请求异常: ${error.message || "未知错误"}`);
        historicalData.value = [];
      } finally {
        loading.value.historical = false;
      }
    };

    // 页面操作方法
    const refreshMetrics = async () => {
      await fetchMetrics();
      await fetchHealth();
    };

    const refreshAlerts = () => {
      fetchAlerts();
    };

    const handleSizeChange = (size) => {
      pagination.value.pageSize = size;
      fetchAlerts();
    };

    const handlePageChange = (page) => {
      pagination.value.pageNum = page;
      fetchAlerts();
    };

    // 生命周期钩子
    onMounted(() => {
      refreshMetrics();
      refreshAlerts();
      // 初始化默认时间范围
      initDefaultDateRange();
      // 自动获取历史数据
      fetchHistoricalData();

      // 设置定时刷新
      refreshTimer = setInterval(() => {
        refreshMetrics();
      }, 60000); // 每分钟刷新一次系统指标和健康状态
    });

    onBeforeUnmount(() => {
      // 清理定时器
      if (refreshTimer) {
        clearInterval(refreshTimer);
      }
    });

    return {
      currentMetrics,
      healthReport,
      alerts,
      pagination,
      loading,
      getProgressColor,
      getAlertLevelType,
      getAlertLevel,
      getAlertType,
      formatDateTime,
      refreshMetrics,
      refreshAlerts,
      handleSizeChange,
      handlePageChange,
      dateRange,
      historicalData,
      fetchHistoricalData,
    };
  },
};
</script>

<style scoped>
.monitor-container {
  padding: 20px;
}

.page-title {
  color: #303133;
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: 600;
}

.dashboard-row {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.update-time {
  font-size: 12px;
  color: #909399;
  margin-right: 10px;
}

.health-card {
  height: 100%;
  transition: all 0.3s;
}

.healthy {
  border-top: 4px solid #67c23a;
}

.unhealthy {
  border-top: 4px solid #f56c6c;
}

.health-report {
  padding: 10px 0;
}

.report-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.report-label {
  color: #606266;
  font-weight: 500;
}

.report-value {
  color: #303133;
  font-weight: 600;
}

.metrics-dashboard {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  margin: 20px 0;
}

.metric-gauge {
  text-align: center;
  margin-bottom: 20px;
}

.metric-title {
  margin-bottom: 15px;
  font-weight: 500;
  color: #606266;
}

.metric-value {
  margin-top: 10px;
  font-size: 16px;
  color: #303133;
  font-weight: 600;
}

.metrics-detail {
  padding: 10px 0;
}

.metric-detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.detail-label {
  width: 150px;
  color: #606266;
  font-weight: 500;
}

.detail-value {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 10px;
}

.alert-card {
  margin-top: 20px;
}

.pagination-container {
  padding: 15px 0;
  display: flex;
  justify-content: flex-end;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .metrics-dashboard {
    flex-direction: column;
    align-items: center;
  }

  .metric-detail-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .detail-label {
    width: 100%;
    margin-bottom: 5px;
  }

  .detail-value {
    width: 100%;
  }
}
.history-card {
  margin-top: 20px;
}

.date-range-picker {
  display: flex;
  align-items: center;
  gap: 10px;
}

.empty-data {
  padding: 40px 0;
  text-align: center;
}

.chart-container {
  margin-top: 20px;
}

.metrics-table {
  margin-top: 20px;
}
</style>